package org.qufenqi.api.filter;

import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/login/*",filterName = "loginFilter")
public class LoginFilter implements Filter {

    //注入redis
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取令牌
        String token =request.getHeader("token");
        //获取令牌对应剩余时间
        Long expire = redisTemplate.getExpire(token);

        //已经登录，放行
        if(expire > 0)
        {
            filterChain.doFilter(servletRequest,servletResponse);
        }
        else{
            response.sendRedirect("/account/login");
        }
    }
}
